package com.vf.admin.fiwork.controller.live;

import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.client.tx.utils.txConfig;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.AppUser;
import com.vf.admin.miaodong.service.AfterUserService;
import com.vf.admin.fiwork.util.AgoraTokenUtil;
import com.vf.admin.fiwork.util.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.vf.admin.client.common.ClientConstants.client_toke;


/**
 * 聊天相关控制器
 */
@Controller
@RequestMapping("/app/rtm")
public class RtmManageController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AfterUserService appUserService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 创建聊天TOKEN签名
     * @return
     */
    @RequestMapping("/createRtmToken")
    @ResponseBody
    public Result createToken(Integer type) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            AppUser user = appUserService.get(userId);
            if(Objects.isNull(user)) return this.errorJSON("User does not exist");
            String token  = null;
            if(type.equals(1)){
                token = AgoraTokenUtil.rtmTokenBuilder(userId.toString());
            }else if(type.equals(2)){
                token = TxIm.createImSign(userId.toString());
            }else{
                return this.errorJSON("Type error");
            }
            return this.sucessJSON(token, "成功");
        }catch (Exception e){
            e.printStackTrace();
            return this.errorJSON(e.getMessage());
        }
    }

    /**
     * 推送聊天消息
     * @param groupId 群组ID
     * @return
     */
    @PostMapping("/sendmsg")
    @ResponseBody
    public Result sendmsg(String groupId,String msg) {
        if(sendmsgAll(groupId, msg,1)){
            return sucessJSON("成功");
        }else{
            return sucessJSON("Fail in send");
        }
    }

    /**
     * 推送聊天消息
     * @param GroupId 群组ID
     * 1 = 管理员发送信息
     * 2 = 发送加入直播间用户信息
     * 3 = 发送礼物信息
     * 4 = 关闭直播间
     * 5 = 送礼物
     * 6 = PK刷礼物
     * 7 = PK邀请发送信息
     * @return
     */
    public boolean sendmsgAll(String GroupId,Object msg,Integer type) {
        if (StringUtils.isBlank(GroupId) || Objects.isNull(msg)) return false;
        Integer number = RandomUtil.randomFromTo(1, 2147483646);
        String adminSign = TxIm.createImSign("administrator");
        //发送系统通知
//      String urlNotis = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification?sdkappid="+ txConfig.SDKAPPID+"&identifier=administrator&usersig=" + adminSign + "&random=" + number + "&contenttype=json";
       //发送普通消息
        String url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid="+ txConfig.SDKAPPID+"&identifier=administrator&usersig=" + adminSign + "&random=" + number + "&contenttype=json";
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        //RestTemplate带参传的时候要用HttpEntity<?>对象传递
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("GroupId", GroupId);
        //无符号32位整数。如果5分钟内两条消息的随机值相同，后一条消息将被当做重复消息而丢弃
        map.put("Random",  RandomUtil.randomFromTo(1, 2147483646));
        JSONObject MsgBody = new JSONObject();
        MsgBody.put("MsgType", "TIMCustomElem");
        JSONObject MsgContent = new JSONObject();
        MsgContent.put("Desc", "notification");
        //定义data数据格式
        JSONObject datContent = new JSONObject();
        datContent.put("data", msg);
        datContent.put("type", type);
        MsgContent.put("Data", datContent.toJSONString());
        MsgBody.put("MsgContent", MsgContent);
        ArrayList<Object> arrayList = new ArrayList<>();
        arrayList.add(MsgBody);
        map.put("MsgBody", arrayList);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(map, headers);
        JSONObject jsonObject = restTemplate.postForObject(url, request, JSONObject.class);
        logger.info("----------------------"+jsonObject+"------------------------------");
        if(Objects.isNull(jsonObject) || !jsonObject.getString("ActionStatus").equals("OK")) return false;
        return true;
    }

}
